import {
	defineStore
} from "pinia";

import io from '@hyoga/uni-socket.io';

export const useSocket = defineStore("ivmcr.socket", () => {
	let client = undefined;
	let baseUrl = "wss://demo.soullightstheworld.com"
	// let baseUrl = "wss://appapi.ivmcr.com"
	let heartbeatInterval = null;
	// 心跳发送的间隔时间（秒）  
	let time = 10;
	let isOpen = false;
	
	// 记录上一次接收到 pong 消息的时间
	let lastPongTime = new Date().getTime();

	// 连接
	function connect() {
		const token = uni.getStorageSync('token')

		if (!token) {
			console.log("重新登录")
			return false;
		}

		if (!client) {
			const option = {
				cors: {
					origin: "*",
					methods: ["GET", "POST"]
				},
				transports: ['websocket', 'polling'],
				timeout: 5000,
				// pingInterval: 30000, // 每隔 30 秒发送一次心跳包
				// pingTimeout: 5000 // 如果在 5 秒内未收到心跳响应，则认为连接中断
			}

			uni.showLoading({
				title: "加载中",
				mask: true
			})

			client = io(baseUrl, option);

			client.on("connect", () => {
				console.log("[cs] connect");

				console.log('connect to server!');
				console.log(client.id);

				uni.hideLoading();
				
				// 设置心跳间隔，默认是25秒
				client.io.engine.pingInterval = 25000;
				// 设置心跳超时时间，默认是25秒
				client.io.engine.pingTimeout = 25000;

				client.emit('authentication', {
					auth: token
				});
				
				isOpen = true;
				startHeartbeat()
			});

			// 监听ping事件，即心跳检测
			client.on('ping', () => {
				console.log('Heartbeat received.');

			});
			// 监听pong事件，即心跳响应
			client.on('pong', (latency) => {
				
				// lastPongTime = new Date().getTime();
				
				console.log('Heartbeat acknowledged with latency: ' +
					latency + 'ms.');
			});

			// 客户端每隔 10 秒检查一次是否收到 pong 消息
			// setInterval(function() {
			//   const now = new Date().getTime();
			//   if (now - lastPongTime > 30000) {
			// 	// 超过 30 秒没有收到 pong 消息，认为连接断开，进行相应的处理
				
				
			//   }
			// }, 10000);


			client.on('authenticated', function() {
				console.log("认证成功")
			});

			client.on('connect_error', function(error) {
				console.log("[cs] connect_error", error);
				isOpen = false;
			});

			client.on("disconnect", () => {
				console.log("[cs] disconnect");
				isOpen = false;
			});
			
			
			
		}
	}

	// 启动心跳检测  
	function startHeartbeat() {
		if (heartbeatInterval) {
			clearInterval(heartbeatInterval);
		}
		heartbeatInterval = setInterval(() => {
			console.log(11111111);
			client.emit('ping',{});
		}, time * 1000);
	}


	// 断开连接
	function disconnect() {
		client?.disconnect();
		clearInterval(this.heartbeatInterval);
		client = undefined;
		 this.isOpen = false; 
	}


	function event(content) {
		if (this.socket) {
			// 发送事件
			this.socket.emit("event", content);
		} else {
			console.log("[cs] client error");
		}
	}

	function say(content) {
		if (this.socket) {
			// 发送事件
			this.socket.emit("say", JSON.stringify(content));
		} else {
			console.log("[cs] client error");
		}
	}

	function joinRoom(content) {

		if (this.socket) {
			// 发送事件
			this.socket.emit("join-room", JSON.stringify(content));
		} else {
			console.log("[cs] client error");
		}
	}

	// 监听退出
	uni.$on("user.logout", () => {
		disconnect();
	});

	return {
		connect,
		client,
		event,
		say,
		joinRoom
	};
});